# -*- coding:utf-8 -*-

"""
model:Source
ID:
title:Performance-开机速度-011-HDMI信源下STR开机到能调节音量
Precondition：
1、HDMI：22293输入亮条彩纹
2、电视开启STR
Description：
1、在HDMI上STR待机
2、按遥控器“Power”键启动电视
3、在电视启动过程中一直按音量“加”键
4、计算从按下Power键到进入HDMI1和显示音量条所需时间（启动到可操作时间）
TestResult:
1、3-3.4秒内完成启动并可操作
level：
Author：pantsing
date:2018/8/31
"""
from TST.Accessory import *
import TLog
import TMenu
import TBoot
import TPeripheral
import TPerformance
import TFile
import Image
import os
import numpy
import re
import shutil

# 声明变量
Performance = TPerformance.get_class()
result = []
time_list = []
script_id = "Boot_Speed_011"

# 标准时间， 每一帧时间
STANDARD_TIME = 3.4
frame_time = 0.0334

# 处理测试结果
def test_result():
    if len(time_list) == TPerformance.TEST_COUNT and numpy.mean(time_list) <= STANDARD_TIME:
        TLog.r("测试结果: Pass.", TLog.DOUBLE_LINES)
        TestResult.Pass("\\n".join(result))
    else:
        TLog.e("测试结果: Fail!", TLog.DOUBLE_LINES)
        TLog.e("\\n".join(result))
        TestResult.Fail("\\n".join(result))


def save_as(index):
    cnt = 0
    file_dict = {}
    file_path = r"%s\TCache" % os.path.dirname(TFile._BASE_BOX_DIR)
    for file_name in os.listdir(file_path):
        old_path = os.path.join(file_path, file_name)
        if TFile.exists(old_path):
            cnt += 1
            num = int(re.findall("\d+", file_name)[-1])
            new_path = TFile.filename(r"Performance\%s\Test_%d\%s" % (script_id, index, file_name))
            file_dict[num] = new_path
            shutil.move(old_path, new_path)
    return file_dict, cnt


def remote_key(key_name, pic_time):
    TPeripheral.get_remote().sendKey("power")
    TPeripheral.get_remote().sendKey(key_name, pic_time*4, 0.25)


def take_pic(pic_name, pic_time):
    TPeripheral.get_video_capture().takePictureWithtimes(TFile.filename(pic_name), pic_time)


def main():
    try:
        dir_path = TFile.filename(r"Performance\%s" %script_id)
        if TFile.exists(dir_path):
            shutil.rmtree(dir_path)
        if "Volume_Location3" in dir(Performance):
            Volume_Location3 = Performance.Volume_Location3
        else:
            Volume_Location3 = Performance.Volume_Location2

        rgb1_standard, rgb2_standard, rgb3_standard = TPerformance.read_volume_rgb()
        TLog.d("标准的rgb--rgb1:%s rgb2:%s rgb3:%s" % (rgb1_standard, rgb2_standard, rgb3_standard))
        for index in range(1, TPerformance.TEST_COUNT + 1):
            TLog.i("[第%d次测试]" % index, TLog.TOP_LINE)
            if TBoot._system_running() != 1:
                result.append("第%s次测试：打开电视失败!" % index)
                continue
            if not TMenu.move("source", "hdmi1"):
                result.append("第%s次测试：切信源到HDMI1失败!" % index)
                continue
            TLog.i("执行待机开机操作")
            TMenu.send_keys(["power", 5])
            TFile.remove_all()
            threads = []
            pic_time = 10
            t1 = threading.Thread(target=take_pic, args=("p.bmp", pic_time))
            threads.append(t1)
            t2 = threading.Thread(target=remote_key, args=("volume+", pic_time))
            threads.append(t2)
            for t in threads:
                t.setDaemon(True)
                t.start()
            t.join()
            timer = -1
            file_dict, cnt = save_as(index)
            frame_time = float(pic_time) / float(cnt)
            frame_time = round(frame_time, 4)
            TLog.i("第%s次测试：每帧画面的平均时长为：%f" % (index, frame_time))
            if pic_time < 11:
                abs_count = 3
            else:
                abs_count = 5
            if abs(TPerformance.FRAME_COUNT * pic_time - cnt) > abs_count:
                TLog.i("第%s次测试：截图的个数和一秒30帧相差比较大，此次作废" % index)
                result.append("第%s次测试：截图的个数和一秒30帧相差比较大，此次作废" % index)
                cnt = 0
            for i in range(cnt):
                new_path = file_dict[i]
                im = Image.open(new_path)
                Pixel = im.load()
                rgb1 = Pixel[Performance.Volume_Location1[0],Performance.Volume_Location1[1]]
                rgb2 = Pixel[Performance.Volume_Location2[0],Performance.Volume_Location2[1]]
                rgb3 = Pixel[Volume_Location3[0], Volume_Location3[1]]
                TLog.i("第%s次测试：下标是%s图选定坐标rgb1：%s rgb2:%s rgb3:%s" % (index, i, rgb1, rgb2, rgb3))
                if TPerformance.rgb_in(rgb1_standard, rgb1, 30) and TPerformance.rgb_in(
                        rgb2_standard, rgb2, 30) and TPerformance.rgb_in(rgb3_standard, rgb3, 30):
                    if i > 5:
                        i += 1
                        timer = float(i * pic_time)/cnt
                        time_list.append(timer)
                        result.append("第%s次测试：HDMI信源下STR开机到能调节音量时间为%s秒" % (index, timer))
                        result.append("%s Test_%d 下标是_%d张" % (script_id, index, i - 1))
                        TLog.i("第%s次测试：HDMI信源下STR开机到能调节音量时间为%s秒" % (index, timer))
                        TLog.i("第%s次测试：HDMI信源下STR开机到能调节音量出现画面路径为：%s" % (index, new_path))
                        TLog.i("第%s次测试：HDMI信源下STR开机到能调节音量截取的第%s张图片" % (index, i))
                        break
                    else:
                        continue
            if timer == -1:
                result.append("第%s次测试，HDMI信源下STR开机到能调节音量时间: 失败!" % index)
            time.sleep(20)
            if len(time_list) > 2 and numpy.max(time_list) - numpy.min(time_list) < numpy.mean(time_list)/TPerformance.Mean_Count:
                break
    finally:
        TLog.i("测试结束.", TLog.DOUBLE_LINES)
        avg_time = "Unknown"
        if time_list:
            avg_time = numpy.mean(time_list)
            max_time = numpy.max(time_list)
            min_time = numpy.min(time_list)
            result.append("HDMI信源下STR开机到能调节音量时间平均值: %s秒，最大值: %s秒，最小值: %s秒." % (avg_time, max_time, min_time))
        for txt in result:
            TLog.i(txt)
        TPerformance.write_to_excel(u"STR开机到能调节音量+-(HDMI)", avg_time)


# 释放资源
def close_peripheral():
    try:
        TPeripheral.get_remote().close()
        TPeripheral.get_video_capture().close()
        TPeripheral.get_serial().close()
        # TPeripheral.get_web_ui().close()
    except Exception as e:
        TLog.record_log("close_peripheral()")
        result.append("释放外设资源时发生异常(Exception: %s)!" % e)
    except:
        TLog.record_log("close_peripheral()")
        result.append("释放外设资源时发生异常(未知类型异常)!")


def open_peripheral():
    TPeripheral.get_web_ui()
    TPeripheral.get_remote()
    TPeripheral.get_video_capture()
    TPeripheral.get_serial()


def pre_condition():
    try:
        if TBoot._system_running() != 1:
            result.append("打开电视失败!")
            return False
        if TBoot.set_str_on() != TBoot.SUCCESS:
            result.append("STR设置为开无效")
            return False
        return True
    finally:
        TPeripheral.get_serial().close()


if __name__ == "__main__":
    try:
        TLog.test_start()
        open_peripheral()
        if pre_condition():
            main()
    except BaseException as e:
        TLog.record_log(script_id)
        result.append("程序发生异常!")
    finally:
        close_peripheral()
        TLog.test_end()
        test_result()